#!/usr/bin/env python
# coding: utf-8

# In[1]:


import sys
import random
from PySide2.QtWidgets import QApplication, QWidget, QTextEdit, QHBoxLayout
from PySide2.QtCore import QFile, QDir, QTimer, Slot, Qt, QThread, Signal
from PySide2.QtGui import QClipboard, QIcon, QPixmap
from Spider import *

# In[2]:
#创建翻译器
class WorkerThread(QThread):
    resultReady = Signal()
    def __init__(self):
        super().__init__()

    def __del__(self):
        pass

    def run(self):
        global translation
        translation = Translation()
        self.resultReady.emit()

#翻译线程
class WorkerThreadTrans(QThread):
    resultReady = Signal(str)
    def __init__(self):
        super().__init__()
        self.last = ''

    def __del__(self):
        pass

    def setText(self, value):
        self.value = value

    def run(self):
        self.result = ''
        while(not self.isInterruptionRequested()):
            self.getClipborad()
            QThread.sleep(1)

    @Slot()
    def getClipborad(self):
        global translation
        board = QApplication.clipboard()
        self.str = board.text()
        if self.str == '' or self.str == self.last:
            pass
        else:
            try:
                self.last = self.str
                self.result = translation.translate(self.str)
            except:
                pass
            finally:
                pass
            self.resultReady.emit(self.result)

#窗口
class Form(QWidget):
    def __init__(self):
        super().__init__()
        
        self.textEdit = QTextEdit()
        self.layout = QHBoxLayout()
        self.layout.addWidget(self.textEdit)
        self.setLayout(self.layout)
        
        self.setWindowTitle("百度翻译器")
        self.resize(400, 300)
        self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.icon = QIcon()
        self.icon.addPixmap(QPixmap('favicon.ico'), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(self.icon)

        self.create = False

        self.thread = WorkerThread()
        self.thread.finished.connect(self.thread.deleteLater)
        self.thread.resultReady.connect(self.createTrans)
        self.thread.start()

        self.threadTrans = WorkerThreadTrans()
        self.threadTrans.resultReady.connect(self.setTextValue)

        
    def __del__(self):
        pass
    
    @Slot()
    def createTrans(self):
        self.create = True
        self.threadTrans.start()

    @Slot()
    def setTextValue(self, value):
        self.textEdit.setPlainText(value)

    def closeEvent(self, event):
        global translation
        self.threadTrans.requestInterruption()
        self.threadTrans.quit()
        self.threadTrans.wait()
        if self.create:
            del translation
        super().closeEvent(event)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    translation = None

    window = Form()
    window.show()

    sys.exit(app.exec_())



